<?php
// +----------------------------------------------------------------------
// | OneKeyAdmin [ Believe that you can do better ]
// +----------------------------------------------------------------------
// | Copyright (c) 2020-2023 http://onekeyadmin.com All rights reserved.
// +----------------------------------------------------------------------
// | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 )
// +----------------------------------------------------------------------
// | Author: MUKE <513038996@qq.com>
// +----------------------------------------------------------------------
namespace plugins\blog\api\controller;

use think\exception\ValidateException;
use app\api\BaseController;
use plugins\blog\api\validate\UserBlog as Validate;
use app\api\model\Config;
use app\api\model\User;
use plugins\blog\api\model\Blog;
/**
 * 我的博客
 */
class UserBlog extends BaseController
{
    /**
     * 用户权鉴
     */
    public $middleware = [\app\api\middleware\AuthCheck::class];


    protected function initialize()
    {
        parent::initialize();
        $this->config = Config::getVal('app_blog');
        if (! $this->config) {
            $this->config = [
                'page'           => 10,
                'field'          => [],
                'captcha'        => 1,
                'release_review' => 1,
                'release_limit'  => 10,
            ];
        }
    }
    /**
     * 显示资源列表
     */
    public function index()
    {
        if ($this->request->isPost()) {
            try {
                $input = input('post.');
                validate(Validate::class)->scene('index')->check($input);
            } catch ( ValidateException $e ) {
                return json(['status' => 'error', 'message' => $e->getError()]);
            }
            $where[] = ['user_id', '=', $this->request->userId];
            $count = Blog::withSearch(['keyword','date'], $input)->where($where)->count();
            $data  = Blog::withSearch(['keyword','date'], $input)
            ->where($where)
            ->order('create_time', 'desc')
            ->append(['content_images','comment_count','collect_count'])
            ->page($input['page'], 10)
            ->select();
            return json(['status' => 'success','message' => '获取成功', 'data' => $data, 'count' => $count]);
        }
    }
    
    /**
     * 保存新建的资源
     */
    public function save() 
    {
        if ($this->request->isPost()) {
            $input = input('post.');
            if ($this->config['captcha'] == 1) {
                if (empty($input['code'])) {
                    return json(["status" => "error", "message" => '请填写验证码']);
                }
                if (! password_verify($input['code'], $input['rcode'])) {
                    return json(["status" => "error", "message" => '验证码错误']);
                }
            }
            try {
                validate(Validate::class)->scene('save')->check($input);
            } catch ( ValidateException $e ) {
                return json(['status' => 'error', 'message' => $e->getError()]);
            }
            $count = Blog::where('user_id', $this->request->userId)->whereDay('create_time')->count();
            if ($count === $this->config['release_limit']) {
                return json(['status' => 'error', 'message' => '每日最多发布'.$this->config['release_limit'].'篇文章']);
            }
            $author = User::where('user_id', $this->request->userId)->value('nickname');
            $data   = Blog::create([
                'user_id'              => $this->request->userId,
                'group_id'             => [],
                'catalog_id'           => $input['catalog_id'],
                'relation'             => [],
                'title'                => $input['title'],
                'c_title'              => '',
                'description'          => '',
                'author'               => $author,
                'content'              => $input['content'],
                'cover'                => '',
                'images'               => [],
                'seo_url'              => "",
                'seo_title'            => $input['title'],
                'seo_keywords'         => "",
                'seo_description'      => "",
                'field'                => [],
                'istop'                => 0,
                'isrecommend'          => 0,
                'ishot'                => 0,
                'clicks'               => 0,
                'create_time'          => date('Y-m-d H:i:s'),
                'status'               => $this->config['release_review'],
                'sort'                 => 0
            ]);
            return json(['status' => 'success', 'message' => '发布成功', 'data' => $data]);
        }
    }
    
    /**
     * 保存更新的资源
     */
    public function update() 
    {
        if ($this->request->isPost()) {
            try {
                $input = input('post.');
                validate(Validate::class)->scene('update')->check($input);
            } catch ( ValidateException $e ) {
                return json(['status' => 'error', 'message' => $e->getError()]);
            }
            $data = [
                'id'         => $input['id'],
                'user_id'    => $this->request->userId,
                'catalog_id' => $input['catalog_id'],
                'title'      => $input['title'],
                'content'    => $input['content'],
                'status'     => $this->config['release_review'],
            ];
            Blog::update($data);
            return json(['status' => 'success', 'message' => '修改成功', 'data' => $data]);
        }
    }

    /**
     * 删除指定资源
     */
    public function delete()
    {
        if ($this->request->isPost()) {
            try {
                $input = input('post.');
                validate(Validate::class)->scene('delete')->check($input);
            } catch ( ValidateException $e ) {
                return json(['status' => 'error', 'message' => $e->getError()]);
            }
            Blog::where('id', $input['id'])->where('user_id', $this->request->userId)->delete();
            return json(['status' => 'success','message' => '删除成功']);
        }
    }
}